#include "button.h"

#include <assert.h>
#include <stdlib.h>
#include <string.h>

void Button_OnInit(STWnd *wnd)
{
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton *button = (STButton *)wnd;
    DEBUG_LOG("Button_OnInit");
}

void Button_OnDestroy(STWnd *wnd)
{
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton *button = (STButton *)wnd;
    DEBUG_LOG("Button_OnDestroy");
}

void Button_OnPaint(STWnd *wnd)
{
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton *button = (STButton *)wnd;
    // wnd->driver->FillRect(&(wnd->rect));
    wnd->driver->DrawRect(&(wnd->rect));
    STRect conRect = wnd->rect;
    conRect.width -= 4;
    conRect.height -= 4;
    conRect.p.x += 2;
    conRect.p.y += 2;
    wnd->driver->DrawStr(L"button", &conRect);
    DEBUG_LOG("Button_OnPaint isClickable: %d", button->isClickable);
}

void Button_SetText(STWnd *wnd, const char *text)
{
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton *button = (STButton *)wnd;
    const STWndVApi *vtbl = (const STWndVApi *)wnd->vApi;
    // 触发重绘
    if (vtbl->OnPaint) {
        vtbl->OnPaint(wnd);
    }
}

bool Button_OnEvent(STWnd *wnd, STKeyEvent ev)
{
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton *button = (STButton *)wnd;
    g_wndApi.TriggerEvent(wnd, EVENT_CLICK);
    return true;
}

void Button_SetIsClick(STWnd *wnd, bool value)
{
    assert(wnd->type == WND_TYPE_BUTTON);
    STButton *button = (STButton *)wnd;
    button->isClickable = value;
}

// 标签创建函数
STButton *CreateButton()
{
    static const STWndVApi buttonVtbl = {
        .OnInit = Button_OnInit,
        .OnDestroy = Button_OnDestroy,
        .OnPaint = Button_OnPaint,
        .OnEvent = Button_OnEvent};

    STButton *button = (STButton *)(g_wndApi.CreateWndEx(sizeof(STButton), WND_TYPE_BUTTON, &buttonVtbl));
    if (button) {
        button->SetIsClick = Button_SetIsClick;
    }
    return button;
}
